﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Marbles.Core.Content.Assets;
using Marbles.Core.Content.Sites;

namespace Marbles.Core.Handlers
{
    public class AssetHandler : HttpHandlerBase, IHttpHandlerBase
    {

        public void ProcessRequest(HttpContext context)
        {
            string assetid = string.Empty;
            bool attachment = false;

            if (!string.IsNullOrEmpty(context.Request.Params["id"])) { assetid = context.Request.Params["id"]; }
            if (!string.IsNullOrEmpty(context.Request.Params["attachment"])) { attachment = Convert.ToBoolean(context.Request.Params["attachment"]); }

            if (string.IsNullOrEmpty(assetid))
            {
                context.Response.ContentType = "text/html";
                context.Response.Write("Asset not found.");
                context.Response.End();
                return;
            }

            Asset asset = new Asset(SiteDefinition.GetCurrent().SiteId, assetid);
            asset.UpdateLastAccess();

            if (string.IsNullOrEmpty(context.Request.Params["attachment"]))
            {
                if ((asset.IsImage) || (asset.IsVideo))
                {
                    asset.Download(context.Response, false);
                }
                else
                {
                    asset.Download(context.Response, true);
                }
            }
            else
            {
                asset.Download(context.Response, attachment);
            }
        }

        public string Verbs
        {
            get { return "GET"; }
        }

        public bool Validate
        {
            get { return false; }
        }

        public string Path
        {
            get { return "Asset.axd"; }
        }

        public string Name
        {
            get { return this.GetType().Name; }
        }

        public bool IsReusable
        {
            get { return false; }
        }

    }
}